package com.bit.blog.common.advice;

import com.bit.blog.pojo.response.Result;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.ControllerAdvice;

//进行统一结果返回的相关处理；
@ControllerAdvice
public class ResponseBodyAdvice implements org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice {
@Autowired
private ObjectMapper objectMapper;
//使用这个类可以使得对象进行序列化；

    @Override
    public boolean supports(MethodParameter returnType, Class converterType) {
        return true;
    }
    @SneakyThrows//异常的处理注解；
    @Override
    public Object beforeBodyWrite(Object body, MethodParameter returnType, MediaType selectedContentType, Class selectedConverterType, ServerHttpRequest request, ServerHttpResponse response) {
        if(body instanceof String){
           return objectMapper.writeValueAsString(Result.success(body));
            //将成功后返回的字符串转化为原本的字符串；
        }
        if(body instanceof Result){
            return body;
        }
        return Result.success(body);
    }
}
